package com.edu.gdkm.filter;

import com.edu.gdkm.dao.dypDao;
import com.edu.gdkm.util.cookiesUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebFilter("/index.html")
public class loginFilter implements Filter {
    private cookiesUtil ckeUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 获取工具类
        ckeUtil = new cookiesUtil();
    }

    /**
     * 自动登录拦截器
     * 查询 => Cookie dyp_user
     * 截取 => 用户名 、 ID
     * 查询 => 数据库 -> 返还密码
     * 重定向 => loginServlet
     * 否则 => 放行 -> index.html
     * */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 类型转换
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        if (req.getCookies() != null){
            // 查询 => Cookie dyp_user
            Cookie c = ckeUtil.findCookie(req.getCookies(), "dyp_user");
            if (c.getValue() != null){
                // 截取 => 用户名 、 ID
                String userName = ckeUtil.splitCookies(c)[0];
                String id = ckeUtil.splitCookies(c)[1];
                // 查询 => 数据库
                String pwd;
                try {
                    dypDao dao = new dypDao();
                    // 数据库 -> 密码
                    /* 用户 */
                    pwd = dao.resultFirst(
                            dao.select("cpwd", "customer", "cname="+dao.str(userName)+" and cid="+id));
                    if (pwd != null){
                        // 重定向 => loginServlet
                        resp.sendRedirect(
                                req.getContextPath()+
                                        "/loginServlet?userName="+userName+"&pwd="+pwd);
                        dao.close();
                        return;
                    }
                    /* 管理员 */
                    pwd = dao.resultFirst(
                            dao.select("apwd", "category", "aname="+dao.str(userName)+" and aid="+id));
                    if (pwd != null){
                        resp.sendRedirect(
                                req.getContextPath()+
                                        "/loginServlet?userName="+userName+"&pwd="+pwd);
                        dao.close();
                        return;
                    }
                } catch (SQLException | ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        // 放行 -> index.html
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
